<template>
  <div class="teacher-management-container">
    <el-card class="search-card">
      <div class="search-header">
        <h2>教师管理</h2>
        <el-button type="primary" @click="handleAddTeacher">添加教师</el-button>
      </div>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入教师姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="searchForm.department" placeholder="请输入所属学院" clearable></el-input>
        </el-form-item>
        <el-form-item label="职称">
          <el-select v-model="searchForm.title" placeholder="请选择职称" clearable style="width: 120px;">
            <el-option v-for="title in titleOptions" :key="title" :label="title" :value="title"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 教师列表 -->
    <el-card class="list-card">
      <el-table 
        :data="teacherList" 
        style="width: 100%" 
        v-loading="loading" 
        border
        @row-click="handleRowClick"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="user.id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="user.username" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="user.realName" label="姓名" min-width="100"></el-table-column>
        <el-table-column prop="teacher.department" label="学院" min-width="150"></el-table-column>
        <el-table-column prop="teacher.title" label="职称" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getTitleTagType(scope.row.teacher.title)">{{ scope.row.teacher.title }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="科研成果" align="center">
          <template #default="scope">
            <div class="achievement-stats">
              <el-tooltip content="项目数量" placement="top">
                <div class="stat-item" @click.stop="showDetails(scope.row, 'projects')">
                  <el-icon><Folder /></el-icon>
                  {{ getApprovedCount(scope.row.projects) }}
                </div>
              </el-tooltip>
              <el-tooltip content="论文数量" placement="top">
                <div class="stat-item" @click.stop="showDetails(scope.row, 'papers')">
                  <el-icon><Document /></el-icon>
                  {{ getApprovedCount(scope.row.papers) }}
                </div>
              </el-tooltip>
              <el-tooltip content="专利数量" placement="top">
                <div class="stat-item" @click.stop="showDetails(scope.row, 'patents')">
                  <el-icon><Medal /></el-icon>
                  {{ getApprovedCount(scope.row.patents) }}
                </div>
              </el-tooltip>
              <el-tooltip content="奖项数量" placement="top">
                <div class="stat-item" @click.stop="showDetails(scope.row, 'awards')">
                  <el-icon><Trophy /></el-icon>
                  {{ getApprovedCount(scope.row.awards) }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="绩效分" width="100" align="center">
          <template #default="scope">
            <span class="score">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click.stop="handleEditTeacher(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click.stop="handleDeleteTeacher(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 详情展示区域 -->
      <div v-if="showDetailPanel" class="detail-panel">
        <div class="detail-header">
          <h3>{{ currentTeacher.user?.realName }} 的{{ detailTypeText }}</h3>
          <div class="detail-tabs">
            <el-radio-group v-model="detailType" size="small">
              <el-radio-button label="projects">科研项目</el-radio-button>
              <el-radio-button label="papers">论文</el-radio-button>
              <el-radio-button label="patents">专利</el-radio-button>
              <el-radio-button label="awards">奖项</el-radio-button>
            </el-radio-group>
            <el-button type="text" @click="closeDetails">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
        
        <!-- 科研项目详情 -->
        <div v-if="detailType === 'projects'" class="detail-content">
          <el-empty v-if="!currentTeacher.projects || currentTeacher.projects.length === 0" description="暂无科研项目数据"></el-empty>
          <el-table v-else :data="currentTeacher.projects" border style="width: 100%">
            <el-table-column prop="name" label="项目名称" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="type" label="项目类型" width="120" align="center">
              <template #default="scope">
                <el-tag :type="getProjectTypeTag(scope.row.type)">{{ getProjectTypeText(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="funding" label="经费(万元)" width="120" align="center"></el-table-column>
            <el-table-column label="项目周期" width="200" align="center">
              <template #default="scope">
                {{ scope.row.startDate }} 至 {{ scope.row.endDate }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 论文详情 -->
        <div v-if="detailType === 'papers'" class="detail-content">
          <el-empty v-if="!currentTeacher.papers || currentTeacher.papers.length === 0" description="暂无论文数据"></el-empty>
          <el-table v-else :data="currentTeacher.papers" border style="width: 100%">
            <el-table-column prop="title" label="论文标题" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="journal" label="期刊" min-width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="impactFactor" label="影响因子" width="100" align="center"></el-table-column>
            <el-table-column prop="publishDate" label="发表日期" width="120" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 专利详情 -->
        <div v-if="detailType === 'patents'" class="detail-content">
          <el-empty v-if="!currentTeacher.patents || currentTeacher.patents.length === 0" description="暂无专利数据"></el-empty>
          <el-table v-else :data="currentTeacher.patents" border style="width: 100%">
            <el-table-column prop="name" label="专利名称" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="type" label="专利类型" width="120" align="center">
              <template #default="scope">
                <el-tag :type="getPatentTypeTag(scope.row.type)">{{ getPatentTypeText(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="authorizationNumber" label="授权号" min-width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="authorizationDate" label="授权日期" width="120" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 奖项详情 -->
        <div v-if="detailType === 'awards'" class="detail-content">
          <el-empty v-if="!currentTeacher.awards || currentTeacher.awards.length === 0" description="暂无奖项数据"></el-empty>
          <el-table v-else :data="currentTeacher.awards" border style="width: 100%">
            <el-table-column prop="name" label="奖项名称" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="level" label="奖项级别" width="120" align="center">
              <template #default="scope">
                <el-tag :type="getAwardLevelTag(scope.row.level)">{{ getAwardLevelText(scope.row.level) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="issuingUnit" label="颁发单位" min-width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="awardDate" label="获奖日期" width="120" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 添加教师对话框 -->
    <el-dialog 
      title="添加教师" 
      v-model="addDialogVisible" 
      width="500px"
    >
      <el-form 
        :model="addForm" 
        :rules="addFormRules" 
        ref="addFormRef" 
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="addForm.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="department">
          <el-input v-model="addForm.department" placeholder="请输入所属学院"></el-input>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-select v-model="addForm.title" placeholder="请选择职称" style="width: 100%">
            <el-option v-for="title in titleOptions" :key="title" :label="title" :value="title"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑教师对话框 -->
    <el-dialog 
      title="编辑教师信息" 
      v-model="editDialogVisible" 
      width="500px"
    >
      <el-form 
        :model="editForm" 
        :rules="editFormRules" 
        ref="editFormRef" 
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editForm.realName" disabled></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="department">
          <el-input v-model="editForm.department" placeholder="请输入所属学院"></el-input>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-select v-model="editForm.title" placeholder="请选择职称" style="width: 100%">
            <el-option v-for="title in titleOptions" :key="title" :label="title" :value="title"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Folder, Document, Medal, Trophy, Close } from '@element-plus/icons-vue'
import axios from 'axios'

// 职称选项
const titleOptions = ['教授', '副教授', '讲师', '助教']

// 获取职称标签类型
const getTitleTagType = (title) => {
  const typeMap = {
    '教授': 'danger',
    '副教授': 'warning',
    '讲师': 'success',
    '助教': 'info'
  }
  return typeMap[title] || 'info'
}

// 获取已审核通过的数量
const getApprovedCount = (items) => {
  if (!items || !Array.isArray(items)) return 0
  return items.filter(item => item.status === 'approved').length
}

// 搜索表单
const searchForm = reactive({
  name: '',
  department: '',
  title: ''
})

// 教师列表数据
const teacherList = ref([])
const loading = ref(false)

// 详情展示相关
const showDetailPanel = ref(false)
const currentTeacher = ref({})
const detailType = ref('projects')
const selectedRowIndex = ref(null)

// 详情类型文本
const detailTypeText = computed(() => {
  const typeMap = {
    'projects': '科研项目',
    'papers': '论文',
    'patents': '专利',
    'awards': '奖项'
  }
  return typeMap[detailType.value] || ''
})

// 获取项目类型标签
const getProjectTypeTag = (type) => {
  const typeMap = {
    'national': 'danger',
    'provincial': 'warning',
    'municipal': 'success',
    'horizontal': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取项目类型文本
const getProjectTypeText = (type) => {
  const typeMap = {
    'national': '国家级',
    'provincial': '省级',
    'municipal': '市级',
    'horizontal': '横向'
  }
  return typeMap[type] || type
}

// 获取专利类型标签
const getPatentTypeTag = (type) => {
  const typeMap = {
    'invention': 'danger',
    'utility_model': 'warning',
    'design': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取专利类型文本
const getPatentTypeText = (type) => {
  const typeMap = {
    'invention': '发明专利',
    'utility_model': '实用新型',
    'design': '外观设计'
  }
  return typeMap[type] || type
}

// 获取奖项级别标签
const getAwardLevelTag = (level) => {
  const levelMap = {
    'national': 'danger',
    'provincial': 'warning',
    'municipal': 'success',
    'school': 'info'
  }
  return levelMap[level] || 'info'
}

// 获取奖项级别文本
const getAwardLevelText = (level) => {
  const levelMap = {
    'national': '国家级',
    'provincial': '省级',
    'municipal': '市级',
    'school': '校级'
  }
  return levelMap[level] || level
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex === selectedRowIndex.value) {
    return 'selected-row'
  }
  return ''
}

// 处理行点击
const handleRowClick = (row, column, event) => {
  // 如果已经选中了这一行，则关闭详情面板
  if (currentTeacher.value === row && showDetailPanel.value) {
    closeDetails()
    return
  }
  
  // 否则显示详情
  showDetails(row, 'projects')
}

// 显示详情
const showDetails = (teacher, type) => {
  currentTeacher.value = teacher
  detailType.value = type
  showDetailPanel.value = true
  
  // 找到当前行的索引
  selectedRowIndex.value = teacherList.value.findIndex(item => item === teacher)
}

// 关闭详情
const closeDetails = () => {
  showDetailPanel.value = false
  selectedRowIndex.value = null
}

// 添加对话框相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const submitLoading = ref(false)

// 添加表单
const addForm = reactive({
  username: '',
  password: '',
  realName: '',
  department: '',
  title: ''
})

// 添加表单验证规则
const addFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入所属学院', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ]
}

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)

// 编辑表单
const editForm = reactive({
  id: null,
  userId: null,
  username: '',
  realName: '',
  department: '',
  title: ''
})

// 编辑表单验证规则
const editFormRules = {
  department: [
    { required: true, message: '请输入所属学院', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ]
}

// 获取教师列表
const fetchTeacherList = async () => {
  loading.value = true
  try {
    const response = await axios.post('http://localhost:8081/api/teacher/list', {
      name: searchForm.name,
      department: searchForm.department,
      title: searchForm.title
    })
    if (response.data.code === 200) {
      teacherList.value = response.data.data || []
      console.log('获取到的教师列表数据:', teacherList.value)
    } else {
      ElMessage.error(response.data.msg || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表错误:', error)
    ElMessage.error('获取教师列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 搜索教师
const handleSearch = () => {
  fetchTeacherList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchTeacherList()
}

// 添加教师
const handleAddTeacher = () => {
  resetAddForm()
  addDialogVisible.value = true
}

// 重置添加表单
const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  
  addForm.username = ''
  addForm.password = ''
  addForm.realName = ''
  addForm.department = ''
  addForm.title = ''
}

// 提交添加表单
const submitAddForm = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 先添加用户
        const userResponse = await axios.post('http://localhost:8081/api/user/add', {
          username: addForm.username,
          password: addForm.password,
          realName: addForm.realName,
          role: 'teacher'
        })
        
        if (userResponse.data.code === 200) {
          const userId = userResponse.data.data.uid
          
          // 再添加教师信息
          const teacherResponse = await axios.post('http://localhost:8081/api/teacher/add', {
            userId: userId,
            department: addForm.department,
            title: addForm.title
          })
          
          if (teacherResponse.data.code === 200) {
            ElMessage.success('添加教师成功')
            addDialogVisible.value = false
            fetchTeacherList() // 刷新列表
          } else {
            ElMessage.error(teacherResponse.data.msg || '添加教师信息失败')
          }
        } else {
          ElMessage.error(userResponse.data.msg || '添加用户失败')
        }
      } catch (error) {
        console.error('添加教师错误:', error)
        ElMessage.error('添加教师失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 编辑教师
const handleEditTeacher = (row) => {
  editForm.id = row.teacher.id
  editForm.userId = row.teacher.userId
  editForm.username = row.user.username
  editForm.realName = row.user.realName
  editForm.department = row.teacher.department
  editForm.title = row.teacher.title
  
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const response = await axios.post('http://localhost:8081/api/teacher/update', {
          id: editForm.id,
          userId: editForm.userId,
          department: editForm.department,
          title: editForm.title
        })
        
        if (response.data.code === 200) {
          ElMessage.success('编辑教师信息成功')
          editDialogVisible.value = false
          fetchTeacherList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || '编辑教师信息失败')
        }
      } catch (error) {
        console.error('编辑教师错误:', error)
        ElMessage.error('编辑教师信息失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除教师
const handleDeleteTeacher = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除教师 "${row.user.realName}" 吗？此操作将不可逆！`,
      '删除教师',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const params = new URLSearchParams()
    params.append('id', row.teacher.id)
    
    const response = await axios.post('http://localhost:8081/api/teacher/delete', params)
    
    if (response.data.code === 200) {
      ElMessage.success('删除教师成功')
      fetchTeacherList() // 刷新列表
    } else {
      ElMessage.error(response.data.msg || '删除教师失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除教师错误:', error)
      ElMessage.error('删除教师失败，请检查网络连接')
    }
  }
}

// 页面加载时获取教师列表
onMounted(() => {
  fetchTeacherList()
})
</script>

<style scoped>
.teacher-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-top: 15px;
}

.list-card {
  margin-bottom: 20px;
}

.achievement-stats {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  cursor: pointer;
  padding: 2px 5px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.stat-item:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.score {
  font-weight: bold;
  color: #F56C6C;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}

:deep(.selected-row) {
  background-color: #ecf5ff !important;
}

/* 详情面板样式 */
.detail-panel {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-tabs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-content {
  margin-top: 10px;
}

:deep(.el-table--border) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-radio-button__inner) {
  padding: 8px 15px;
}
</style>
